﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XWeb.Core
{
    public class EntityRepository<TEntity> where TEntity : class
    {
        private DbContext _dbContext;

        public EntityRepository(DbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void Create(TEntity entity)
        {
            _dbContext.Set<TEntity>().Add(entity);
        }

        public void Update(TEntity entity)
        {
            _dbContext.Entry<TEntity>(entity).State = System.Data.Entity.EntityState.Modified;
        }

        public void Delete(TEntity entity)
        {
            _dbContext.Entry<TEntity>(entity).State =  System.Data.Entity.EntityState.Deleted;
        }

        public TEntity Get(Func<TEntity, bool> predicate)
        {
            return _dbContext.Set<TEntity>().Where(predicate).SingleOrDefault();
        }

        public TEntity First(Func<TEntity, bool> predicate)
        {
            return _dbContext.Set<TEntity>().Where(predicate).FirstOrDefault();
        }

        public int Count(Func<TEntity, bool> predicate)
        {
            return _dbContext.Set<TEntity>().Count(predicate);
        }
        public int Count()
        {
            return _dbContext.Set<TEntity>().Count();
        }

        public List<TEntity> GetList(Func<TEntity, bool> predicate)
        {
            return _dbContext.Set<TEntity>().Where(predicate).ToList();
        }
        public IEnumerable<TEntity> Query(Func<TEntity, bool> predicate)
        {
            return _dbContext.Set<TEntity>().Where(predicate);
        }

        public IEnumerable<TEntity> Query()
        {
            return _dbContext.Set<TEntity>();
        }
    }
}
